package com.block.merchant.service.impl;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.*;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantDataAllocateInfoMapper;
import com.block.im.enums.UserTypeEnum;
import com.block.im.model.dto.IMHttpResultDTO;
import com.block.im.model.param.ImUserParam;
import com.block.im.service.IImBaseCommonService;
import com.block.im.service.IMsgHandleService;
import com.block.merchant.service.IMerchantDataAllocateInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.merchant.service.IMerchantDataPoolInfoService;
import com.block.merchant.service.IMerchantUserInfoService;
import com.block.sms.dto.SmsParamDTO;
import com.block.sms.service.ISmsConfigInfoService;
import com.block.sms.service.ISmsRecordService;
import com.block.sms.service.ISmsTemplateService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 * 公海数据分配表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-11-02
 */
@Service
public class MerchantDataAllocateInfoServiceImpl extends ServiceImpl<MerchantDataAllocateInfoMapper, MerchantDataAllocateInfo> implements IMerchantDataAllocateInfoService {

    private static final Logger log = LogFactory.getMerchantLog();

    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IMerchantDataPoolInfoService merchantDataPoolInfoService;
    @Autowired
    IMerchantUserInfoService merchantUserInfoService;
    @Autowired
    ISmsRecordService smsRecordService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    ISmsConfigInfoService smsConfigInfoService;
    @Autowired
    ISmsTemplateService smsTemplateService;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;
    @Autowired
    IMsgHandleService msgHandleService;

    /**
     * crm 自动分配 给 业务员
     */
    @Override
    @Transactional
    public void  autoAllocateToUser(String poolDataId){

        try {
            // 查询公海信息
            MerchantDataPoolInfo dataPoolInfo = merchantDataPoolInfoService.getById(poolDataId);
            if (ObjectUtil.isEmpty(dataPoolInfo)){
                //
                log.info("【crm自动分配】公海数据为空【poolDataId】{}", poolDataId);
                return;
            }
            if (ObjectUtil.equals(dataPoolInfo.getStatus(), Integer.valueOf(1))){
                // 已经分配过了
                log.info("【crm自动分配】数据已经分配过了【poolDataId】{}", poolDataId);
                return;
            }

            MerchantUserInfo merchantUserInfo = merchantUserInfoService.getCanPushUserInfo(dataPoolInfo.getInfoId());
            if (ObjectUtil.isEmpty(merchantUserInfo)){
                // 没有可以推送的业务员信息
                log.info("【crm自动分配】可推送业务员信息为空【infoId】{}", dataPoolInfo.getInfoId());
                return;
            }
            // 查询可推送的用户信息
            MerchantDataAllocateInfo allocateInfo = this.saveToUser(dataPoolInfo, merchantUserInfo);
            if (ObjectUtil.isEmpty(allocateInfo)){
                log.info("【crm自动分配】分配失败，记录为空【infoId】{}【userInfo}", dataPoolInfo.getInfoId(), merchantUserInfo.getUid());
                return;
            }

            MerchantDataPoolInfo updatePoolInfo = new MerchantDataPoolInfo();
            updatePoolInfo.setId(dataPoolInfo.getId());
            updatePoolInfo.setStatus(1);
            updatePoolInfo.setUserId(Long.valueOf(merchantUserInfo.getUid()));
            boolean update = merchantDataPoolInfoService.updateById(updatePoolInfo);
            log.info("【crm自动分配】更新公海信息【update】{}【infoId】{}【userInfo】{}",
                    update, dataPoolInfo.getInfoId(), merchantUserInfo.getUid());
            if (!update){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }

            // 更新最后推送时间
            MerchantUserInfo updateUserInfo = new MerchantUserInfo();
            updateUserInfo.setUid(merchantUserInfo.getUid());
            updateUserInfo.setLastPushTime(LocalDateTime.now());
            boolean b = merchantUserInfoService.updateById(updateUserInfo);

            String phone = merchantUserInfo.getPhone();
            if (PhoneUtil.isMobile(phone)){

                SmsParamDTO smsParamDTO = new SmsParamDTO();
                smsParamDTO.setOtype("1");
                smsParamDTO.setMobie(phone);

                MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.getEntityByUidLock(dataPoolInfo.getUid());
                if (ObjectUtil.isNotEmpty(memberSourceInfo)){
                    // 推送，短信提醒
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(DesensitizedUtil.chineseName(memberSourceInfo.getRealname()));
                    jsonArray.add(DesensitizedUtil.mobilePhone(memberSourceInfo.getMobile()));
                    smsParamDTO.setParamArray(jsonArray);

                    ChannelBaseInfo channelBaseInfo = channelCommonService.getBaseInfoByCode(memberSourceInfo.getChannelCode());
                    ApplicationInfo applicationInfo = applicationInfoService.getAppInfoByAppCode(channelBaseInfo.getAppCode());
                    ResponseVo responseVo = smsRecordService.sendSms(smsParamDTO, applicationInfo, channelBaseInfo);
                    log.info("【crm自动分配】业务员发送提醒短信【responseVo】{}", JSON.toJSONString(responseVo));
                }
            }

//            // im消息推送
            ImUserParam fromUser = new ImUserParam(String.valueOf(merchantUserInfo.getUid()), UserTypeEnum.BUS);
            ImUserParam toUser = new ImUserParam(String.valueOf(dataPoolInfo.getUid()), UserTypeEnum.USER);

            String msgContent = StrUtil.format("您好，业务员： {} 随时为您提供贷款咨询服务", merchantUserInfo.getNickName());

            msgHandleService.sendMsg(fromUser, toUser, msgContent);

        }catch (Exception exception){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("POOL_AUTO_ALLOCATE", "crm商户自动分配异常","poolDataId:" + poolDataId, exception);
        }
    }


    public MerchantDataAllocateInfo saveToUser(MerchantDataPoolInfo merchantDataPoolInfo, MerchantUserInfo merchantUserInfo){
        MerchantDataAllocateInfo allocateInfo = new MerchantDataAllocateInfo();

        allocateInfo.setUserId(merchantUserInfo.getUid());
        allocateInfo.setInfoId(merchantDataPoolInfo.getInfoId());
        allocateInfo.setDateInfo(LocalDate.now().toString());
        allocateInfo.setDeptId(merchantDataPoolInfo.getDeptId());
        allocateInfo.setDataId(merchantDataPoolInfo.getId());
        allocateInfo.setUid(merchantDataPoolInfo.getUid());
        allocateInfo.setStatus(1);
        allocateInfo.setType(3);
        boolean save = this.save(allocateInfo);
        if (!save){
            return null;
        }
        return allocateInfo;
    }

}
